package com.cindata

import com.cindata.dictionary.RiskWarningStatusDict
import grails.gorm.transactions.Transactional

@Transactional
class RiskWarningConfigService
{
    static scope = "singleton"

    ComponentService componentService

    def executeCollateral(RiskWarningConfig riskWarningConfig)
    {
        def effectCounts = 0
    	def executeWarningLog = new RiskWarningConfigLog()
        executeWarningLog.riskWarningConfig = riskWarningConfig
        executeWarningLog.logs = "true"
        executeWarningLog.status = "Success"
        executeWarningLog.startTime = new Date()
    	try
        {
        	def rules = RiskWarningConfigRule.findAllByRiskWarningConfig(riskWarningConfig, [sort: 'priority', order: 'desc'])
        	def isAndRelation = riskWarningConfig?.isAndRelation
        	def limitCounts = riskWarningConfig?.limitCounts
            def collateralType = riskWarningConfig?.collateralType
        	def estateStatus = riskWarningConfig?.estateStatus
        	def buildingType = riskWarningConfig?.buildingType
        	def cashability = riskWarningConfig?.cashability
            def riskWarningStatus = RiskWarningStatusDict.findByCode("2")

            def queryParam = new HashMap()
            def executeSql = " from Collateral m where 1=1 and m.estate.id is not null and m.account.id in " + getAccountSql(riskWarningConfig?.bankAccount)
            def sql = " "
            if (collateralType && collateralType != "")
            {
                sql += " and m.type = :collateralType"
                queryParam['collateralType'] = collateralType
            }
            if (estateStatus && estateStatus != "")
            {
                sql += " and m.estateStatus = :estateStatus"
                queryParam['estateStatus'] = estateStatus
            }
            if (cashability && cashability != "")
            {
                sql += " and m.cashability = :cashability"
                queryParam['cashability'] = cashability
            }
            sql += " order by m.modifiedDate desc"
            executeSql += sql
            println executeSql
            def collateralList = Collateral.executeQuery(executeSql, queryParam, [max: limitCounts, offset: 0])
            println "collateralList:" + collateralList
        	if (collateralList) 
        	{
	        	collateralList?.each { collateral ->
	        		def result = null
	        		if (isAndRelation) 
	        		{
	        			result = true
	        			for (rule in rules)
	        			{
	        				def flag = componentService.evaluate(rule?.component, collateral)
			        		if (flag != true) 
			        		{
                                result = false
			        			break
			        		}
	        			}
	        		}
	        		else
	        		{
	        			result = false
	        			for (rule in rules)
	        			{
	        				def flag = componentService.evaluate(rule?.component, collateral)
			        		if (flag == true) 
			        		{
                                result = true
			        			break
			        		}
	        			}
	        		}
	        		if (result)
	        		{
	        			def riskWarning = new RiskWarning()
	        			riskWarning.collateral = collateral
	        			riskWarning.type = riskWarningConfig?.warningType
	        			riskWarning.workflow = riskWarningConfig?.workflow
	        			riskWarning.status = riskWarningStatus
                        riskWarning.bankAccount = riskWarningConfig?.bankAccount // TODO 暂时取当前用户的所属机构，正式定时任务取当前对象的所属机构 collateral.account
                        riskWarning.warningConfig = riskWarningConfig
                        riskWarning.sourceClassType = riskWarningConfig?.sourceClassType
	        			if (riskWarning.validate()) 
	        			{
	        				riskWarning.save flush: true
                            effectCounts++

	        			}
	        			else
	        			{
	        				println riskWarning.errors
	        			}
	        		}
	        	}
	        }
	        else
	        {
	        	executeWarningLog.logs = "未找到满足条件的数据！"
	        	executeWarningLog.status = "Failed"
	        }
        }
        catch(Exception e) 
        {
            e.printStackTrace()
            executeWarningLog.status = "Failed"
            executeWarningLog.logs = e
        }
        
        if (executeWarningLog.validate()) 
        {
            executeWarningLog.logs = "${effectCounts} 条记录受影响！"
            executeWarningLog.endTime = new Date()
            executeWarningLog.save flush: true
        }
        else
        {
            println executeWarningLog.errors
        }
    	return
    }

    def executeMortgage(RiskWarningConfig riskWarningConfig)
    {
        def effectCounts = 0
        def executeWarningLog = new RiskWarningConfigLog()
        executeWarningLog.riskWarningConfig = riskWarningConfig
        executeWarningLog.logs = "true"
        executeWarningLog.status = "Success"
        executeWarningLog.startTime = new Date()
        try
        {
            def rules = RiskWarningConfigRule.findAllByRiskWarningConfig(riskWarningConfig, [sort: 'priority', order: 'desc'])
            def isAndRelation = riskWarningConfig?.isAndRelation
            def limitCounts = riskWarningConfig?.limitCounts

            def riskWarningLevel = riskWarningConfig?.riskWarningLevel
            def mortgageStatus = riskWarningConfig?.mortgageStatus
            def mortgageType = riskWarningConfig?.mortgageType
            def contactType = riskWarningConfig?.contactType
            def riskWarningStatus = RiskWarningStatusDict.findByCode("2")

            def queryParam = new HashMap()
            def executeSql = " from Mortgage m where 1=1 and m.account.id in " + getAccountSql(riskWarningConfig?.bankAccount)
            def sql = " "
            if (riskWarningLevel && riskWarningLevel != "")
            {
                sql += " and m.riskWarningLevel = :riskWarningLevel"
                queryParam['riskWarningLevel'] = riskWarningLevel
            }
            if (mortgageStatus && mortgageStatus != "")
            {
                sql += " and m.mortgageStatus = :mortgageStatus"
                queryParam['mortgageStatus'] = mortgageStatus
            }
            if (mortgageType && mortgageType != "")
            {
                sql += " and m.mortgageType = :mortgageType"
                queryParam['mortgageType'] = mortgageType
            }
            sql += " order by m.modifiedDate desc"
            executeSql += sql

            def mortgageList = Mortgage.executeQuery(executeSql, queryParam, [max: limitCounts, offset: 0])
            if (mortgageList) 
            {
                mortgageList?.each { mortgage ->
                    def result = null
                    if (isAndRelation) 
                    {
                        result = true
                        for (rule in rules)
                        {
                            def flag = componentService.evaluate(rule?.component, mortgage)
                            if (flag != true) 
                            {
                                result = false
                                break
                            }
                        }
                    }
                    else
                    {
                        result = false
                        for (rule in rules)
                        {
                            def flag = componentService.evaluate(rule?.component, mortgage)
                            if (flag == true) 
                            {
                                result = true
                                break
                            }
                        }
                    }
                    if (result)
                    {
                        def riskWarning = new RiskWarning()
                        riskWarning.mortgage = mortgage
                        riskWarning.type = riskWarningConfig?.warningType
                        riskWarning.workflow = riskWarningConfig?.workflow
                        riskWarning.status = riskWarningStatus
                        riskWarning.bankAccount = riskWarningConfig?.bankAccount // TODO 暂时取当前用户的所属机构，正式定时任务取当前对象的所属机构 mortgage.account
                        riskWarning.warningConfig = riskWarningConfig
                        riskWarning.sourceClassType = riskWarningConfig?.sourceClassType
                        if (riskWarning.validate()) 
                        {
                            riskWarning.save flush: true
                            effectCounts++

                        }
                        else
                        {
                            println riskWarning.errors
                        }
                    }
                }
            }
            else
            {
                executeWarningLog.logs = "未找到满足条件的数据！"
                executeWarningLog.status = "Failed"
            }
        }
        catch(Exception e) 
        {
            e.printStackTrace()
            executeWarningLog.status = "Failed"
            executeWarningLog.logs = e
        }
        
        if (executeWarningLog.validate()) 
        {
            executeWarningLog.logs = "${effectCounts} 条记录受影响！"
            executeWarningLog.endTime = new Date()
            executeWarningLog.save flush: true
        }
        else
        {
            println executeWarningLog.errors
        }
        return
    }

    def executeContact(RiskWarningConfig riskWarningConfig)
    {
        def effectCounts = 0
        def executeWarningLog = new RiskWarningConfigLog()
        executeWarningLog.riskWarningConfig = riskWarningConfig
        executeWarningLog.logs = "true"
        executeWarningLog.status = "Success"
        executeWarningLog.startTime = new Date()
        try
        {
            def rules = RiskWarningConfigRule.findAllByRiskWarningConfig(riskWarningConfig, [sort: 'priority', order: 'desc'])
            def isAndRelation = riskWarningConfig?.isAndRelation
            def limitCounts = riskWarningConfig?.limitCounts
            def creditScoreStart = riskWarningConfig?.creditScoreStart
            def creditScoreEnd = riskWarningConfig?.creditScoreEnd
            def riskWarningStatus = RiskWarningStatusDict.findByCode("2")

            def queryParam = new HashMap()
            def executeSql = " from Contact m where 1=1 and m.account.id in " + getAccountSql(riskWarningConfig?.bankAccount)
            def sql = " "
            if (creditScoreStart && creditScoreStart != "")
            {
                sql += " and m.creditScore >= :creditScoreStart"
                queryParam['creditScoreStart'] = creditScoreStart
            }
            if (creditScoreEnd && creditScoreEnd != "")
            {
                sql += " and m.creditScore <= :creditScoreEnd"
                queryParam['creditScoreEnd'] = creditScoreEnd
            }
            sql += " order by m.modifiedDate desc"
            executeSql += sql

            def contactList = Contact.executeQuery(executeSql, queryParam, [max: limitCounts, offset: 0])
            println contactList
            if (contactList) 
            {
                contactList?.each { contact ->
                    def result = null
                    if (isAndRelation) 
                    {
                        result = true
                        for (rule in rules)
                        {
                            def flag = componentService.evaluate(rule?.component, contact)
                            if (flag != true) 
                            {
                                result = false
                                break
                            }
                        }
                    }
                    else
                    {
                        result = false
                        for (rule in rules)
                        {
                            def flag = componentService.evaluate(rule?.component, contact)
                            if (flag == true) 
                            {
                                result = true
                                break
                            }
                        }
                    }
                    if (result)
                    {
                        def riskWarning = new RiskWarning()
                        riskWarning.contact = contact
                        riskWarning.type = riskWarningConfig?.warningType
                        riskWarning.workflow = riskWarningConfig?.workflow
                        riskWarning.status = riskWarningStatus
                        riskWarning.bankAccount = riskWarningConfig?.bankAccount // TODO 暂时取当前用户的所属机构，正式定时任务取当前对象的所属机构 contact.account
                        riskWarning.warningConfig = riskWarningConfig
                        riskWarning.sourceClassType = riskWarningConfig?.sourceClassType
                        if (riskWarning.validate()) 
                        {
                            riskWarning.save flush: true
                            effectCounts++
                        }
                        else
                        {
                            println riskWarning.errors
                        }
                    }
                }
            }
            else
            {
                executeWarningLog.logs = "未找到满足条件的数据！"
                executeWarningLog.status = "Failed"
            }
        }
        catch(Exception e) 
        {
            e.printStackTrace()
            executeWarningLog.status = "Failed"
            executeWarningLog.logs = e
        }
        
        if (executeWarningLog.validate()) 
        {
            executeWarningLog.logs = "${effectCounts} 条记录受影响！"
            executeWarningLog.endTime = new Date()
            executeWarningLog.save flush: true
        }
        else
        {
            println executeWarningLog.errors
        }
        return
    }

    def executeCommunity(RiskWarningConfig riskWarningConfig)
    {
        def effectCounts = 0
        def executeWarningLog = new RiskWarningConfigLog()
        executeWarningLog.riskWarningConfig = riskWarningConfig
        executeWarningLog.logs = "true"
        executeWarningLog.status = "Success"
        executeWarningLog.startTime = new Date()
        try
        {
            def rules = RiskWarningConfigRule.findAllByRiskWarningConfig(riskWarningConfig, [sort: 'priority', order: 'desc'])
            def isAndRelation = riskWarningConfig?.isAndRelation
            def limitCounts = riskWarningConfig?.limitCounts
            def city = riskWarningConfig?.city
            def district = riskWarningConfig?.district
            def riskWarningStatus = RiskWarningStatusDict.findByCode("2")

            def queryParam = new HashMap()
            def executeSql = " from Community m where 1=1 and m.account.id in " + getAccountSql(riskWarningConfig?.bankAccount)
            def sql = " "
            if (city && city != "")
            {
                sql += " and m.city = :city"
                queryParam['city'] = city
            }
            if (district && district != "")
            {
                sql += " and m.district = :district"
                queryParam['district'] = district
            }
            sql += " order by m.modifiedDate desc"
            executeSql += sql
            println executeSql
            def communityList = Community.executeQuery(executeSql, queryParam, [max: limitCounts, offset: 0])
            println communityList
            if (communityList) 
            {
                communityList?.each { community ->
                    def result = null
                    if (isAndRelation) 
                    {
                        result = true
                        for (rule in rules)
                        {
                            def flag = componentService.evaluate(rule?.component, community)
                            if (flag != true) 
                            {
                                result = false
                                break
                            }
                        }
                    }
                    else
                    {
                        result = false
                        for (rule in rules)
                        {
                            def flag = componentService.evaluate(rule?.component, community)
                            if (flag == true) 
                            {
                                result = true
                                break
                            }
                        }
                    }
                    if (result)
                    {
                        def riskWarning = new RiskWarning()
                        riskWarning.community = community
                        riskWarning.type = riskWarningConfig?.warningType
                        riskWarning.workflow = riskWarningConfig?.workflow
                        riskWarning.status = riskWarningStatus
                        riskWarning.bankAccount = riskWarningConfig?.bankAccount // TODO 暂时取当前用户的所属机构，正式定时任务取当前对象的所属机构 contact.community
                        riskWarning.warningConfig = riskWarningConfig
                        riskWarning.sourceClassType = riskWarningConfig?.sourceClassType
                        if (riskWarning.validate()) 
                        {
                            riskWarning.save flush: true
                            effectCounts++
                        }
                        else
                        {
                            println riskWarning.errors
                        }
                    }
                }
            }
            else
            {
                executeWarningLog.logs = "未找到满足条件的数据！"
                executeWarningLog.status = "Failed"
            }
        }
        catch(Exception e) 
        {
            e.printStackTrace()
            executeWarningLog.status = "Failed"
            executeWarningLog.logs = e
        }
        
        if (executeWarningLog.validate()) 
        {
            executeWarningLog.logs = "${effectCounts} 条记录受影响！"
            executeWarningLog.endTime = new Date()
            executeWarningLog.save flush: true
        }
        else
        {
            println executeWarningLog.errors
        }
        return
    }

    def executeAccount(RiskWarningConfig riskWarningConfig)
    {
        def effectCounts = 0
        def executeWarningLog = new RiskWarningConfigLog()
        executeWarningLog.riskWarningConfig = riskWarningConfig
        executeWarningLog.logs = "true"
        executeWarningLog.status = "Success"
        executeWarningLog.startTime = new Date()
        try
        {
            def rules = RiskWarningConfigRule.findAllByRiskWarningConfig(riskWarningConfig, [sort: 'priority', order: 'desc'])
            def isAndRelation = riskWarningConfig?.isAndRelation
            def limitCounts = riskWarningConfig?.limitCounts
            def operatingState = riskWarningConfig?.operatingState
            def riskType = riskWarningConfig?.riskType
            def creditLevel = riskWarningConfig?.creditLevel
            def riskWarningStatus = RiskWarningStatusDict.findByCode("2")

            def queryParam = new HashMap()
            def executeSql = " from Account m where 1=1 m.bankAccount.id in " + getAccountSql(riskWarningConfig?.bankAccount)
            def sql = " "
            if (operatingState && operatingState != "")
            {
                sql += " and m.operatingState = :operatingState"
                queryParam['operatingState'] = operatingState
            }
            if (riskType && riskType != "")
            {
                sql += " and m.id in (select distinct a.account.id from AccountProject a where a.riskType = :riskType)"
                queryParam['riskType'] = riskType
            }
            if (creditLevel && creditLevel != "")
            {
                sql += " and m.creditLevel = :creditLevel"
                queryParam['creditLevel'] = creditLevel
            }
            sql += " order by m.modifiedDate desc"
            executeSql += sql
            def accountList = Account.executeQuery(executeSql, queryParam, [max: limitCounts, offset: 0])
            if (accountList) 
            {
                accountList?.each { account ->
                    def result = null
                    if (isAndRelation) 
                    {
                        result = true
                        for (rule in rules)
                        {
                            def flag = componentService.evaluate(rule?.component, account)
                            if (flag != true) 
                            {
                                result = false
                                break
                            }
                        }
                    }
                    else
                    {
                        result = false
                        for (rule in rules)
                        {
                            def flag = componentService.evaluate(rule?.component, account)
                            if (flag == true) 
                            {
                                result = true
                                break
                            }
                        }
                    }
                    if (result)
                    {
                        def riskWarning = new RiskWarning()
                        riskWarning.account = account
                        riskWarning.type = riskWarningConfig?.warningType
                        riskWarning.workflow = riskWarningConfig?.workflow
                        riskWarning.status = riskWarningStatus
                        riskWarning.bankAccount = riskWarningConfig?.bankAccount // TODO 暂时取当前用户的所属机构，正式定时任务取当前对象的所属机构 account.bankAccount
                        riskWarning.warningConfig = riskWarningConfig
                        riskWarning.sourceClassType = riskWarningConfig?.sourceClassType
                        if (riskWarning.validate()) 
                        {
                            riskWarning.save flush: true
                            effectCounts++
                        }
                        else
                        {
                            println riskWarning.errors
                        }
                    }
                }
            }
            else
            {
                executeWarningLog.logs = "未找到满足条件的数据！"
                executeWarningLog.status = "Failed"
            }
        }
        catch(Exception e) 
        {
            e.printStackTrace()
            executeWarningLog.status = "Failed"
            executeWarningLog.logs = e
        }
        
        if (executeWarningLog.validate()) 
        {
            executeWarningLog.logs = "${effectCounts} 条记录受影响！"
            executeWarningLog.endTime = new Date()
            executeWarningLog.save flush: true
        }
        else
        {
            println executeWarningLog.errors
        }
        return
    }

    def getAccountSql(Account account)
    {
        def accountList = AccountManageAccount.where {
            account == account
        }.manageAccount.list()

        String accountSql = "(" + account?.id + ")"
        if (accountList)
        {
            String accountIdList = accountList*.id?.toString()
            accountSql = "(" + accountIdList?.substring(1, accountIdList.lastIndexOf("]")) + ")"

        }
        return accountSql
    }
}
